package cn.stylefeng.guns.modular.demo.excel.listener.peisong;

import cn.stylefeng.guns.core.exception.BusinessException;
import cn.stylefeng.guns.dao.entity.DistributionDoc;
import cn.stylefeng.guns.dao.entity.SellDoc;
import cn.stylefeng.guns.dao.service.IDistributionDocService;
import cn.stylefeng.guns.dao.service.ISellDocService;
import cn.stylefeng.guns.modular.demo.excel.domain.asilikang.DistributionDocExcelVO;
import cn.stylefeng.guns.modular.demo.excel.domain.asilikang.SellDocExcelVO;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 阿斯利康采购数据
 */
@Slf4j
public class SellDocListener implements ReadListener<SellDocExcelVO> {


    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 1000;
    private List<SellDoc> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);


    private List<String> errorList;
    ISellDocService sellDocService;


    /**
     * 如果使用了spring,请使用这个构造方法。每次创建Listener的时候需要把spring管理的类传进来
     *
     * @param sellDocService
     */
    public SellDocListener(ISellDocService sellDocService, List<String> errorList) {
        this.sellDocService = sellDocService;
        this.errorList = errorList;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. It is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(SellDocExcelVO data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        SellDoc sellDoc = o2o(data);

//        if (keyList.contains(key)) {
//            throw new BusinessException(BusinessExceptionEnum.BUSINESS_DATA_REPEAT, "同一批次内有相同的商品 批次号:" + batch + ",商品名称:" + commodityName);
//        }
//        Goods goods = goodsService.getOne(Wrappers.<Goods>lambdaQuery().eq(Goods::getCommodityCode, goodsCode));
//        if (Objects.isNull(goods)) {
//            throw new BusinessException(BusinessExceptionEnum.BUSINESS_DATA_REPEAT, "商品不存在" + goodsCode);
//        }

//        Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery().eq(Supplier::getName, supplierName));
//        if (Objects.isNull(supplier)) {
//            throw new BusinessException(BusinessExceptionEnum.BUSINESS_DATA_REPEAT, "供应商不存在" + supplierName);
//        }


        cachedDataList.add(sellDoc);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    private SellDoc o2o(SellDocExcelVO distributionDocExcelVO) {
        if (distributionDocExcelVO == null) {
            return null;
        }
        SellDoc sellDoc = new SellDoc();
        sellDoc.setTime(distributionDocExcelVO.getSellTime().getTime());

        sellDoc.setStoCode(distributionDocExcelVO.getStoCode());

        sellDoc.set应收金额(distributionDocExcelVO.get应收金额());
        sellDoc.set实收金额(distributionDocExcelVO.get实收金额());
        sellDoc.set加点后成本额(distributionDocExcelVO.get加点后成本额());
        sellDoc.set毛利额(distributionDocExcelVO.get毛利额());
        sellDoc.set毛利率(distributionDocExcelVO.get毛利率());
        sellDoc.set品单价(distributionDocExcelVO.get品单价());
        sellDoc.set客品次(distributionDocExcelVO.get客品次());
        sellDoc.set客品数(distributionDocExcelVO.get客品数());
        sellDoc.set现金(distributionDocExcelVO.get现金());
        sellDoc.set现金折扣金额(distributionDocExcelVO.get现金折扣金额());
        sellDoc.set聚合收(distributionDocExcelVO.get聚合收());
        sellDoc.set聚合收折扣金额(distributionDocExcelVO.get聚合收折扣金额());
        sellDoc.set银联(distributionDocExcelVO.get银联());
        sellDoc.set银联折扣金额(distributionDocExcelVO.get银联折扣金额());
        sellDoc.set医保(distributionDocExcelVO.get医保());
        sellDoc.set医保折扣金额(distributionDocExcelVO.get医保折扣金额());
        sellDoc.set美团(distributionDocExcelVO.get美团());
        sellDoc.set美团折扣金额(distributionDocExcelVO.get美团折扣金额());
        sellDoc.set饿了么(distributionDocExcelVO.get饿了么());
        sellDoc.set饿了么折扣金额(distributionDocExcelVO.get饿了么折扣金额());
        sellDoc.set储值卡(distributionDocExcelVO.get储值卡());
        sellDoc.set储值卡折扣金额(distributionDocExcelVO.get储值卡折扣金额());
        sellDoc.set现金券(distributionDocExcelVO.get现金券());
        sellDoc.set现金券折扣金额(distributionDocExcelVO.get现金券折扣金额());
        sellDoc.set消费券(distributionDocExcelVO.get消费券());
        sellDoc.set消费券折扣金额(distributionDocExcelVO.get消费券折扣金额());
        sellDoc.set抵用券(distributionDocExcelVO.get抵用券());
        sellDoc.set抵用券折扣金额(distributionDocExcelVO.get抵用券折扣金额());
        sellDoc.set电子折扣券(distributionDocExcelVO.get电子折扣券());
        sellDoc.set电子折扣券折扣金额(distributionDocExcelVO.get电子折扣券折扣金额());
        sellDoc.set积分抵现额(distributionDocExcelVO.get积分抵现额());
        sellDoc.set积分抵现额折扣金额(distributionDocExcelVO.get积分抵现额折扣金额());
        sellDoc.set赊账(distributionDocExcelVO.get赊账());
        sellDoc.set赊账折扣金额(distributionDocExcelVO.get赊账折扣金额());
        sellDoc.set好乐多(distributionDocExcelVO.get好乐多());
        sellDoc.set好乐多折扣金额(distributionDocExcelVO.get好乐多折扣金额());
        sellDoc.set健E卡(distributionDocExcelVO.get健E卡());
        sellDoc.set健E卡折扣金额(distributionDocExcelVO.get健E卡折扣金额());
        sellDoc.set美团b2c(distributionDocExcelVO.get美团b2c());
        sellDoc.set美团b2c折扣金额(distributionDocExcelVO.get美团b2c折扣金额());
        sellDoc.set普康宝(distributionDocExcelVO.get普康宝());
        sellDoc.set普康宝折扣金额(distributionDocExcelVO.get普康宝折扣金额());
        sellDoc.set拼多多(distributionDocExcelVO.get拼多多());
        sellDoc.set拼多多折扣金额(distributionDocExcelVO.get拼多多折扣金额());
        sellDoc.set浙里金消(distributionDocExcelVO.get浙里金消());
        sellDoc.set浙里金消折扣金额(distributionDocExcelVO.get浙里金消折扣金额());
        sellDoc.set天猫(distributionDocExcelVO.get天猫());
        sellDoc.set天猫折扣金额(distributionDocExcelVO.get天猫折扣金额());
        sellDoc.set淘宝(distributionDocExcelVO.get淘宝());
        sellDoc.set淘宝折扣金额(distributionDocExcelVO.get淘宝折扣金额());
        sellDoc.set京东b2c(distributionDocExcelVO.get京东b2c());
        sellDoc.set京东b2c折扣金额(distributionDocExcelVO.get京东b2c折扣金额());
        sellDoc.set药房网(distributionDocExcelVO.get药房网());
        sellDoc.set药房网折扣金额(distributionDocExcelVO.get药房网折扣金额());
        sellDoc.setOMS线上支付(distributionDocExcelVO.getOMS线上支付());
        sellDoc.setOMS线上支付折扣金额(distributionDocExcelVO.getOMS线上支付折扣金额());
        sellDoc.set对公打款(distributionDocExcelVO.get对公打款());
        sellDoc.set对公打款折扣金额(distributionDocExcelVO.get对公打款折扣金额());
        sellDoc.set微商城(distributionDocExcelVO.get微商城());
        sellDoc.set微商城折扣金额(distributionDocExcelVO.get微商城折扣金额());
        sellDoc.set购物卡(distributionDocExcelVO.get购物卡());
        sellDoc.set购物卡折扣金额(distributionDocExcelVO.get购物卡折扣金额());
        sellDoc.setData(JSON.toJSONString(distributionDocExcelVO));
        return sellDoc;
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) {
        log.error("解析失败，但是继续解析下一行:{}", exception.getMessage());
        // 如果是某一个单元格的转换异常 能获取到具体行号
        // 如果要获取头的信息 配合invokeHeadMap使用
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            log.error("第{}行，第{}列解析异常，数据为:{}", excelDataConvertException.getRowIndex(), excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData());
            errorList.add("第" + excelDataConvertException.getRowIndex() + "行，第" + excelDataConvertException.getColumnIndex() + "列解析异常，数据为:" + excelDataConvertException.getCellData());
        }

        if (exception instanceof BusinessException) {
            errorList.add(exception.getMessage());
        } else {
            log.info("数据错误解析错误", exception);
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        try {
            log.info("{}条数据，开始存储数据库！", cachedDataList.size());
            sellDocService.saveBatch(cachedDataList);
            log.info("存储数据库成功！");
        } catch (Exception e) {
            log.info("数据错误", e);
            throw e;
        }
    }

}
